#include "bdd.h"

racine *root_head;
session **sess_tab;
uint sess_top;
char *bdd_path;
uint td_err;
char *tdversion;

subbase *
add_subbase (subbase * par, subbase * head, char *id, byte c_s)
{
  uint len;
  subbase *n = malloc (sizeof (subbase));
  len = strlen (id);
  n->ident = malloc (len + 1);
  strcpy (n->ident, id);
  if (c_s == NO_CASE_SENS)
    low_string (n->ident);
    
  n->hash = chksum_crc32 (n->ident, len);
  n->parent = par;
  par->enfant = n;
  n->enfant = NULL;
  n->next = head;
  n->prev = NULL;
  n->rows = NULL;
  if (head)
    head->prev = n;
  return (n);
}

racine *
add_base (racine * head, char *id, byte c_s)
{
  uint len;
  racine *n = malloc (sizeof (racine));
  n->base = malloc (sizeof (subbase));
  len = strlen (id);
  n->base->ident = malloc (len + 1);
  strcpy (n->base->ident, id);
  n->case_flag = c_s;
  if (c_s == NO_CASE_SENS)
    low_string (n->base->ident);
  n->base->hash = chksum_crc32 (n->base->ident, len);

  n->base->parent = NULL;
  n->base->enfant = NULL;
  n->base->next = NULL;
  n->base->prev = NULL;
  n->base->rows = NULL;

  n->next = head;
  n->prev = NULL;
  if (head)
    head->prev = n;

  return (n);
}

row *
add_row (row * head, char *id, char *va, byte c_s)
{
  uint len;
  row *n = malloc (sizeof (row));
  len = strlen (id);
  n->ident = malloc (len + 1);
  n->val = malloc (strlen (va) + 1);
  strcpy (n->ident, id);
  if (c_s == NO_CASE_SENS)
    low_string (n->ident);
  strcpy (n->val, va);
  n->hash = chksum_crc32 (n->ident, len);
  n->next = head;
  n->prev = NULL;
  if (head)
    head->prev = n;
  return (n);
}

uint
add_session ()
{
  uint a;
  for (a = 1; a < sess_top; a++)
    if (!sess_tab[a])
      {
	*(sess_tab + a) = malloc (sizeof (session));
	sess_tab[a]->subptr = NULL;
	sess_tab[a]->rowptr = NULL;
	sess_tab[a]->baseptr = NULL;
	sess_tab[a]->rootptr = NULL;
	return a;
      }

  if (!sess_top)
    sess_tab = malloc (sizeof (session *));

  else
    sess_tab = realloc (sess_tab, (sess_top + 1) * sizeof (session *));

  *(sess_tab + sess_top) = malloc (sizeof (session));

  sess_tab[sess_top]->subptr = NULL;
  sess_tab[sess_top]->rowptr = NULL;
  sess_tab[sess_top]->baseptr = NULL;
  sess_tab[sess_top]->rootptr = NULL;

  sess_top++;
  return (sess_top - 1);
}
